import { useMemo } from 'react';
import { useSplitPaths } from '.';

/**
 * @typedef {{ ...Resource, children: ResourceTree, isExact: Boolean }} MatchedMenu   菜单节点
 */

/**
 * 根据当前路由获取匹配的菜单节点 (resource)
 * @param {ResourceTree} menuTree         在此菜单树中匹配
 * @param {Boolean} [exact = false]       是否准确匹配 (如果为true 子页面将不会匹配到父页面菜单节点)
 * @param {String} [prefix = '/']         路径前缀
 * @return {MatchedMenu|null}
 */
function useCurrentMenu(menuTree, { exact = false, prefix = '/' } = {}) {
  const paths = useSplitPaths(prefix);
  return useMemo(() => {
    let currentMenu = { children: menuTree };
    let isExact = true;
    if (!paths.length) {
      const nextMenu = (currentMenu?.children ?? []).find((item) => !item.url) || null;
      if (!nextMenu) {
        if (exact) currentMenu = null;
        isExact = false;
      } else {
        currentMenu = nextMenu;
      }
    }
    for (let i = 0; i < paths.length; i++) {
      const url = paths[i];
      const nextMenu = (currentMenu?.children ?? []).find((item) => item.url === url) || null;
      if (!nextMenu) {
        if (exact) currentMenu = null;
        isExact = false;
        break;
      }
      currentMenu = nextMenu;
    }
    if (!currentMenu) return null;

    return {
      ...currentMenu,
      isExact,
    };
  }, [paths, menuTree]);
}

export default useCurrentMenu;
